<template>
  <div id="labNodeSetting">
    <Breadcrumb content="标本流转节点设置" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="25">
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <div class="smallToolTitle">节点设置</div> -->
              <!-- <vxe-input clearable placeholder="关键字查询" class="vxeInputSearch" v-model="keywords" @search-click="search"
              @keyup="keyup" type="search"></vxe-input>-->
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getProcessSetList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="handleAdd"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-save" content="保存" :loading="showLoading" class="button-blue" @click="saveList"></vxe-button>
              <vxe-button type="text" class="button-red" icon="vxe-icon-delete" content="删除" @click="handleDeleteProcessSet"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="tableRef" align="left" border height="auto" class="mytable-scrollbar" :loading="showLoading" :data="processSetList" @current-change="tableCellClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: true, showStatus: true }" resizable show-overflow>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="workFlowCode" title="编码" width="60" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ row.workFlowCode ? row.workFlowCode : '' }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.workFlowCode" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="workFlowName" title="方案名称" min-width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ row.workFlowName ? row.workFlowName : '' }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.workFlowName" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="reportTemplateId" title="报表模板" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-select v-model="row.reportTemplateId" placeholder="请选择报表模板">
                    <vxe-option v-for="(item, index) in reportTemplateList" :key="index" :label="item.name" :value="item.id"></vxe-option>
                  </vxe-select>
                </template>
                <template #default="{ row }"> {{ getReportTemplateName(row) }}</template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="60" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ row.seq }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.seq" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="75">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="节点设置" name="first">
              <Splitpanes class="area">
                <Pane size="55">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <!-- <div class="smallToolTitle">节点设置</div> -->
                      <!-- <vxe-input clearable placeholder="关键字查询" class="vxeInputSearch" v-model="keywords" @search-click="search"
              @keyup="keyup" type="search"></vxe-input>-->
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" @click="getNodeDict"></vxe-button>
                      <vxe-button type="text" icon="vxe-icon-save" content="保存" :loading="nosLoading" class="button-blue" @click="saveNodeList"></vxe-button>
                      <!-- <vxe-button
                type="text"
                class="button-red"
                icon="vxe-icon-delete"
                content="删除"
                @click="handleDeleteProcessSet"
              ></vxe-button>-->
                      <span style="color:red;margin-left:10px;">*双击后取消选择</span>
                    </template>
                  </vxe-toolbar>
                  <div class="tableBox">
                    <vxe-table ref="tableRefNode" align="left" border height="auto" class="mytable-scrollbar" :loading="showLoading" :data="flowNodeList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: true
                  }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false, showStatus: true }" resizable show-overflow keep-source @cell-dblclick="deleteProcessNode">
                      <vxe-column field="nodeTypeNa" title="节点类型" width="60"></vxe-column>
                      <vxe-column field="nodeCode" title="编码" width="80"></vxe-column>
                      <vxe-column field="nodeName" title="名称" min-width="120"></vxe-column>
                      <vxe-column field="explain" title="说明" min-width="120"></vxe-column>
                      <vxe-column field="pageName" title="应用界面" min-width="120"></vxe-column>
                      <vxe-column field="seq" title="顺序" :edit-render="{}">
                        <template #default="{ row }">
                          <span>{{ row.seq }}</span>
                        </template>
                        <template #edit="{ row }">
                          <vxe-input v-model="row.seq" type="text"></vxe-input>
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
                <Pane size="45">
                  <div class="tableBox">
                    <span>节点属性信息 </span><span style="color:red;">*双击选择节点</span>
                    <vxe-table ref="antibioticsDictTable" border="inner" align="left" class="mytable-scrollbar" height="500" :data="bacWorkFlowNodeDictList" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: true
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source @current-change="roleRowClick" @cell-dblclick="addProcessNode">
                      <vxe-column field="nodeTypeNa" title="节点类型" width="60"></vxe-column>
                      <vxe-column field="code" title="编码" width="80"></vxe-column>
                      <vxe-column field="name" title="名称" min-width="120"></vxe-column>
                      <vxe-column field="seq" title="序号" width="60"></vxe-column>
                      <vxe-column field="displayFlag" title="显示标志" width="100"></vxe-column>
                      <vxe-column field="displayColor" title="显示颜色" width="80">
                        <template #default="{ row }">
                          <el-color-picker v-model="row.displayColor" />
                        </template>
                      </vxe-column>
                      <!-- <vxe-column field="standardName" title="编号前缀" width="80"></vxe-column>
                  <vxe-column field="codePrefix" title="编号规则编码" width="100"></vxe-column>
                  <vxe-column field="isPrintLabel" title="是否打印标签" width="90"></vxe-column>
                  <vxe-column field="isEnable" title="是否启用" width="80"></vxe-column>-->
                    </vxe-table>
                    <div style="margin-top:10px;" v-if="nodeDict">
                      <el-form label-width="100">
                        <el-form-item label="节点详细说明：">{{nodeDict.explain}}</el-form-item>
                        <el-form-item label="应用页面：">{{nodeDict.pageName}}</el-form-item>
                        <el-form-item label="适合操作：">{{nodeDict.operation}}</el-form-item>
                      </el-form>
                    </div>
                  </div>
                  <ExtraPropertyPanel :busRow="curSlectRow" />
                </Pane>
              </Splitpanes>
            </el-tab-pane>
            <el-tab-pane label="阴性结果默认值" name="second" :disabled="IsEmpty(processId)">
              <BacFlowDefResult ref="flowDefResultRef" />
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========src\views\lab_sys\bac_set\BacGermDict.vue
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
//import LabNodeSettingForm from './LabNodeSettingForm.vue';//基本信息表单组件
import ExtraPropertyPanel from '@/components/ExtraPropertyPanel.vue';
import { IsEmpty, formatDateTime, autoIncrementNumber } from '@/utils/common';
import BacFlowDefResult from './BacFlowDefResult.vue'; //失控记录图表

// 全局变量定义区 ==========

let { proxy }: any = getCurrentInstance();
let flowDefResultRef: any = ref(null);

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

// 页面标题
let content = ref('标本流转节点设置');
// 用户输入关键字
let keywords = ref('');
let curIndex = ref(-1); /**保存时记录当前选中索引，更换新完数据后 再次选中改行 */

let activeName = ref('first');

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存
let flowNodeList = reactive([]);
let processId = ref(null);
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
const refUnqualifiedReason = ref<InstanceType<typeof refUnqualifiedReason>>(); //属性信息表单标记ref
let currentRow: any = reactive({ id: '', code: '' }); //基本信息表单当前行数据
// 模块功能表格数据
let processSetList: any = reactive([]);
let bacWorkFlowNodeDictList: any[] = reactive([]); //流程节点字典列表
const reportTemplateList = reactive([]); //报表模板列表
let nodeDict = ref({});
const curSlectRow = ref({});
//**判断为空*/
let IsEmpty = (value: any) => {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
};

// 方法定义区 =============
onMounted(() => {
  getProcessSetList();
  getDictMeasureList();
  // getModulePointMap();
});

function getReportTemplateName(row: any) {
  for (const item of reportTemplateList) {
    if (item.id == row.reportTemplateId) {
      return item.name;
    }
  }
}
//获取报表模板列表
function getDictMeasureList() {
  reportTemplateList.length = 0;
  const url = '/api/pubReport/getReportList';
  proxy.$http
    .get(url, { params: { pageIndex: 1, pageSize: 50, type: 0, dictDetailCode: 'pointsCode', dictDetailValue: '006' } })
    .then((res: any) => {
      reportTemplateList.push(...res.data.reportList.records);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 请求表格数据
function getProcessSetList() {
  showLoading.value = true;
  let pageParam = {
    params: {
      keywords: keywords.value
    }
  };
  processSetList.length = 0; //放入数据前清空数组
  proxy.$http.get('/api/bac/bac-work-flow/findBacWorkFlowList', pageParam).then(async (res: any) => {
    if (res.status.code === 1) {
      showLoading.value = false;
      // console.log('模块数据列表', res.status.code);
      processSetList.push(...res.data);
      if (res && res.data && res.data.length > 0) {
        currentRow.id = '';
        tableCellClick({ row: res.data[0] });
        const $table = tableRef.value;
        if ($table) {
          await $table.setCurrentRow(res.data[0]);
        }
      }
    } else {
      showLoading.value = false;
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}

// 表格选中当前行
function tableCellClick({ row }: any) {
  processId.value = row.workFlowCode;
  if (activeName.value == 'first') {
    findAntibioticsDictPageList(row.workFlowCode);
  } else if (activeName.value == 'second') {
    flowDefResultRef.value.initPage(processId.value);
  }
}

function tabHandleClick(tab) {
  if (tab.props.name == 'first') {
    findAntibioticsDictPageList(processId.value);
  } else if (tab.props.name == 'second') {
    flowDefResultRef.value.initPage(processId.value);
  }
}

function getNodeDict() {
  findAntibioticsDictPageList(processId.value);
}

// 新增
async function handleAdd() {
  (proxy.$refs.tableRef as any).clearCurrentRow();
  const row = {
    id: '',
    workFlow: '',
    workFlowName: '',
    reportTemplateId: '',
    seq: processSetList.length + 1 + ''
  };
  processSetList.push(row);
  await tableRef.value?.setCurrentRow(row);
  await tableRef.value?.setEditCell(row, 'templateNo');
  activeName.value = 'first';
  processId.value = '';
}

//保存
function saveList() {
  showLoading.value = true;
  const row = tableRef.value?.getCurrentRecord();
  curIndex.value = tableRef.value?.getRowIndex(row);
  const data = {
    bacWorkFlows: processSetList
  };
  proxy.$http
    .post('/api/bac/bac-work-flow/addBacWorkFlow', data)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
    });
}

let nosLoading = ref(false);
//保存
async function saveNodeList() {
   let $Xtable = proxy.$refs.tableRefNode;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });

    const sveOrupdateSamples = [] as any[];
    updateRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        nodeCode: e.nodeCode,
        nodeName: e.nodeName,
        nodeUrl: e.nodeUrl,
        nodeUrlName: e.nodeUrlName,
        interfaceCode: e.interfaceCode,
        isEnable: e.isEnable,
        flowNo: e.flowNo,
        nodeDictNo:e.nodeDictNo,
        seq: e.seq
      };

      sveOrupdateSamples.push(iISample);
    });

    if (sveOrupdateSamples.length > 0) {
      const url = '/api/bac/bac-work-flow-node/saveOrUpdateBacWorkFlowNode';
      const obj: any = {};
      obj.bacWorkFlowNodeList = sveOrupdateSamples;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            getNodeDict();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

// 删除
async function handleDeleteProcessSet() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    const newNameArr = [];
    arr.forEach((itm) => {
      if (itm.isSysAtt) {
        newNameArr.push(itm.nodeName);
      }
    });
    let node = newNameArr.join(',');
    if (!IsEmpty(node)) {
      VxeMessage('节点[' + node + ']是系统节点不允许删除', VxeNotifyType.info);
      return;
    }
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { bacWorkFlows: arr };
        const url = '/api/bac/bac-work-flow/deleteBacWorkFlow';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            getProcessSetList();
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        //VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 获取检验仪器表格数据
function findAntibioticsDictPageList(id) {
  bacWorkFlowNodeDictList.length = 0;
  flowNodeList.length = 0;
  const url = '/api/bac/bac-work-flow/findBacWorkFlowNodeDictList';
  proxy.$http
    .get(url, {
      params: {
        settingId: id
      }
    })
    .then((res: any) => {
      bacWorkFlowNodeDictList.push(...res.data.workFlowNodeList);
      flowNodeList.push(...res.data.workFlowList);
      roleRowClick({
        row: bacWorkFlowNodeDictList[0],
        rowIndex: 0
      });
    })
    .catch((err: any) => {
      VxeMessage('搜索流程节点字典列表异常', VxeNotifyType.error);
    });
}
function roleRowClick({ row, rowIndex }: any) {
  (proxy.$refs.antibioticsDictTable as any).setCurrentRow(row);
  nodeDict.value = row;
}

function addProcessNode({ row, rowIndex }: any) {
  const data = { flowNo: processId.value, nodeDictNo: row.code, nodeCode: row.code, nodeName: row.name, nodeUrl: row.nodeUrl, seq: row.seq };
  const url = '/api/bac/bac-work-flow-node/addBacWorkFlowNode';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      findAntibioticsDictPageList(processId.value);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function deleteProcessNode({ row, rowIndex }: any) {
  const data = { flowNo: processId.value, nodeDictNo: row.nodeDictNo };
  const url = '/api/bac/bac-work-flow-node/deleteBacWorkFlowNode';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      findAntibioticsDictPageList(processId.value);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 表格选中当前行
// function tableCellClick({ row }: any) {
//   curSlectRow.value = row;
//   Object.assign(currentRow, row);
//   proxy.$forceUpdate();
// }
</script>
<style lang="scss" scoped>
#labNodeSetting {
  width: 100%;
  height: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .tableBox {
        height: calc(100% - 40px);
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 30px);

          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
